<?php

namespace common;
use support\Db;
class Database
{
    /**
     * 插入数据
     *
     * @param string $table
     * @param array $data
     * @return bool
     */
    public static function insert(string $table, array $data): bool
    {
        return Db::table($table)->insert($data);
    }

    /**
     * 删除数据
     *
     * @param string $table
     * @param array $condition
     * @return int
     */
    public static function delete(string $table, array $condition): int
    {
        return Db::table($table)->where($condition)->delete();
    }

    /**
     * 更新数据
     *
     * @param string $table
     * @param array $condition
     * @param array $data
     * @return int
     */
    public static function update(string $table, array $condition, array $data): int
    {
        return Db::table($table)->where($condition)->update($data);
    }

    /**
     * 查询数据
     *
     * @param string $table
     * @param string|array $columns
     * @param array|null $condition
     * @return array
     */
    public static function select(string $table, $columns = '*', ?array $condition = null,?array $orderby = null,$page = -1): array
    {
        $query = Db::table($table);

        if ($condition) {
            foreach ($condition as $clause) {
                $query->where(...$clause);
            }
        }
        if ($orderby){
            foreach ($orderby as $clause) {
                $query->orderBy(...$clause);
            }
        }
        if ($page>=1){
            $pageSize = 10; // 每页显示的条目数
            $offset = ($page - 1) * $pageSize;
            $limit = $pageSize;
            $query->limit($limit,$offset);
        }
        return $query->select($columns)->get()->toArray();
    }

    /**
     * 连表查询
     *
     * @param string $table
     * @param string $joinTable
     * @param string $joinColumn
     * @param string $tableColumn
     * @param string|array $columns
     * @param array|null $condition
     * @return array
     */
    public static function join(string $table, string $joinTable, string $joinColumn, string $tableColumn, $columns = '*', ?array $condition = null): array
    {
        return Db::table($table)
            ->join($joinTable, $joinColumn, '=', $tableColumn)
            ->where($condition)
            ->select($columns)
            ->get();
    }
}